<script setup>
import { reactive, ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router"
import request from '@/api/request'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'
// 新增：导入ElMessage用于提示
import { ElMessage, ElMessageBox } from 'element-plus'

let router = useRouter();
const rules = reactive({})


let unitId=ref([]);
let isdisabled = ref(true) // 顶部修改按钮禁用状态
let isdisabledreove = ref(true) // 顶部删除按钮禁用状态
let isVisible = ref(false) // 对话框显示状态
let data = ref({}) // 用于传递给修改表单的数据
let title = ref("") // 对话框标题



let page = ref({
    current: 1,
    size: 5,
    total: 0,
    records: []
})

let unitConversion = ref({
    unitId: '',
    unitName: '',
    status: ''
})

// 搜索
const handleSearch = () => {
    page.value.current = 1;
    loadData();
}

// 加载表格数据
let loadData = () => {
    request({
        url: '/unitConversion/index',
        method: 'get',
        params: {
            current: page.value.current,
            size: page.value.size,
            unitId: unitConversion.value.unitId,
            unitName: unitConversion.value.unitName,
            status:unitConversion.value.status
        }
    }).then(res => {
        page.value = res.data
    }).catch(err => {
        ElMessage.error('数据加载失败')
    })
}

loadData();

// 刷新表格
let refTanle = () => {
    isVisible.value = false;
    loadData();
}

// 跳转到新增页面
let toInsert = () => {
    title.value = "新增单位";
    isVisible.value = true;
    router.push("/material/unit/insert");
}

// 修改操作（接收行数据）
let toUpdate = async(row) => {
    data.value = { ...row }; // 深拷贝选中行数据，避免直接修改原数据
    title.value = "修改单位";
    isVisible.value = true;
    if(row!=null){
        data.value=row;
    }else{
        data.value=unitId.value[0];
    }
    router.push("/material/unit/update");
}

// 单条删除
let toRemove = () => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let ids = unitId.value.map(item=>item.unitId)
        request({
            url: "/unitConversion/delete",
            method: "delete",
            data: ids
        }).then(res => {
            ElMessage.success('删除成功')
            loadData()
    })
    })
}
let toRemoves = (id) => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        request({
            url: "/unitConversion/delete",
            method: "delete",
            data: [id]
        }).then(res => {
            ElMessage.success('删除成功')
            loadData()
    })
    })
}

// 表格选择事件：更新选中状态和按钮禁用状态
let fuxuankuang = (a) => {
    unitId.value=a;
}
   

let formRef = ref()

// 重置
let chongzhi = () => {
    unitConversion.value = {
        unitId: '',
        unitName: '',
        status:''
    }
    filterText.value = ''
    expandAllNodes()
    handleSearch()
}



// 新增成功后的回调
const handleAddSuccess = (newUnit) => {
    page.value.records.unshift({
        id: Date.now(),
        unitId: newUnit.unitId,
        unitName: newUnit.unitName,
        isMainUnit: newUnit.isMainUnit,
        conversionRate: newUnit.conversionRate,
        status: newUnit.status 
    })
    page.value.total += 1
    isVisible.value = false
    ElMessage.success('新增成功')
}



</script>

<template>
    <div>
        <el-card>
            <template #header>
                <div>
                    <el-row>
                        

                        <el-col :span="24">
                            <el-form ref="formRef" inline :model="unitConversion"
                                style="display: flex;justify-content: start;" class="card_wrap">
                                <el-form-item label="单位编码" size="default" prop="unitId" class="c_item">
                                    <el-input v-model="unitConversion.unitId" class="sousuo"
                                        placeholder="请输入单位编码" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item label="单位名称" size="default" prop="unitName" class="c_item">
                                    <el-input v-model="unitConversion.unitName" class="sousuo"
                                        placeholder="请输入单位名称" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item class="c_item">
                                    <template #default>
                                        <el-button type="primary" size="default" @click="handleSearch" :icon="Search">搜索</el-button>
                                        <el-button type="info" size="default" :plain=true @click="chongzhi" :icon="Refresh">重置</el-button>
                                    </template>
                                </el-form-item>
                            </el-form>

                            <div style="margin-top: 20px;">
                                <el-button @click="toInsert" type="primary" :plain="true" :icon="Plus">添加</el-button>
                                <!-- 修改：顶部修改按钮绑定新的点击事件handleTopUpdate -->
                                <el-button type="success" size="default" :plain=true @click="toUpdate(null)" :icon="Edit" 
                                    style="border:0px" :disabled="unitId.length!=1">修改</el-button>
                                <!-- 修改：顶部删除按钮绑定批量删除事件handleTopRemove -->
                                <el-button type="danger" size="default" :plain=true @click="toRemove" :icon="Delete" 
                                    style="border:0px" :disabled="!unitId">删除</el-button>
                            </div>

                            <el-table :data="page.records" border stripe @selection-change="fuxuankuang">
                                <el-table-column type="selection" width="55" />

                                <el-table-column prop="unitId" label="单位编码"/>
                                <el-table-column prop="unitName" label="单位名称"/>
                                <el-table-column prop="isMainUnit" label="是否为主单位"  #default="scope">
                                    <el-tag :type="scope.row.isMainUnit=='1' ? 'primary':'danger'">{{ scope.row.isMainUnit=="1" ? "是" :"否"}}</el-tag>
                                </el-table-column>
                                <el-table-column  prop="conversionRate" label="与主单位转换率" />
                                <el-table-column prop="status" label="是否启用" #default="scope">
                                    <el-tag :type="scope.row.status=='1' ? 'primary':'danger'">{{ scope.row.status=="1"?"是":"否"}}</el-tag>
                                </el-table-column>

                                <el-table-column label="操作" fixed="right" >
                                     <template #default="scope">
                                        <el-button size="small" type="primary" @click="toUpdate(scope.row)" :row="scope.row":icon="Edit">修改</el-button>
                                        <el-button size="small" type="danger" @click="toRemoves(scope.row.unitId)" :icon="Delete">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination @current-change="(val) => { page.current = val; loadData() }" 
                                v-model:currentPage="page.current"
                                :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total" background>
                            </el-pagination>
                        </el-col>
                    </el-row>
                    <div style="width:800px">
                        <el-dialog :title="title" v-model="isVisible" :destroy-on-close="true" width="60%">
                            <router-view @ref-table="refTanle" :data="data">
                            </router-view>
                        </el-dialog>
                    </div>
                </div>
            </template>
        </el-card>
    </div>
</template>

<style scoped>
.sousuo {
    width: 200px;
}

.card_wrap {
    width: 98%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.c_item {
    flex: 1;
    margin: 0px 5px 15px 0;
    width: calc((100%-10px)/3);
    min-width: calc((100% - 10px)/3);
    max-width: calc((100% - 10px)/3);

    &:nth-child(3n) {
        margin-right: 0;
    }
}

.filter-tree :deep(.el-tree-node__content) {
    height: auto;
    padding: 5px 0;
}
</style>